package com.service;

import com.dao.QmDao;
import com.dao.UserDao;
import com.entity.User;
import com.entity.UserMetadata;
import com.util.FileUtil;
import com.util.LocalInformation;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import static com.dao.UserDao.readUserInfor;
import static com.dao.UserDao.saveUserInfor;
import static com.dao.UserDao.updateUserInformation;

/**
 * Created by wlc on 2018/3/25.
 */
public class UserOperator {
    /**
     * 注销在线用户列表中指定key值的用户
     * @param key
     */
    public static void log_out(String key){
        String user_file_path = UserMetadata.OnlineUserId.get(key);
        FileUtil.deleteDir(new File(user_file_path));
        UserMetadata.OnlineUserId.remove(key);
        UserMetadata.OnlineUserOperatorTime.remove(key);
    }

    /**
     * 将指定用户信息存储到磁盘并加入在线用户列表
     * @param user_infor
     * @param projectPath
     * @return
     * @throws IOException
     */
    public static String log_in(String user_infor,String projectPath) throws IOException{
        User user = new User();
        //设置用户信息及登录时间
        user.readUserInfor(user_infor);

        //判断用户是否已经登录
        Iterator iter = UserMetadata.OnlineUserId.keySet().iterator();
        while (iter.hasNext()){
            String Online_user_info = iter.next().toString();
            if (Online_user_info.split("wlcniubi")[0].equals(user.getId())){
                UserOperator.log_out(Online_user_info);
                break;
            }
        }

        //存储用户对象数据到磁盘
        String user_file_Path = projectPath+"/file_data/user/"+user.getId()+"/";
        UserDao.saveUserInfor(user,user_file_Path+"information");
        //加入在线用户列表和在线用户操作列表
        String UserMeta_key = user.getId()+"wlcniubi"+user.getUsername()+"wlcniubi"+user.getPermissions()+"wlcniubi"+user.getLogin_time();
        UserMetadata.OnlineUserId.put(UserMeta_key,user_file_Path);
        UserMetadata.OnlineUserOperatorTime.put(UserMeta_key, LocalInformation.getTimeID());

        return UserMeta_key;
    }

    /**
     * 用于从磁盘中获取用户信息
     * @param id
     * @param projectPath
     * @return User
     * @throws IOException
     */
    public static User getUserInformation(String id,String projectPath) throws IOException{
        String user_info_path = projectPath + "/file_data/user/" + id + "/information";
        ArrayList<String> user_info = readUserInfor(user_info_path);
        User user = new User();
        user.setPassword(user_info.get(1));
        user.setRealname(user_info.get(2));
        user.setUniversity(user_info.get(3));
        user.setDepartment(user_info.get(4));
        user.setMail(user_info.get(5));

        return user;
    }

    /**
     * 修改数据库和用户文件信息
     * @param user
     * @param projectPath
     * @throws IOException
     */
    public static void changeUserInformation(User user,String projectPath) throws IOException{
        ArrayList<String> changeField_Data = new ArrayList<String>(){{
            add("idwlcniubi"+user.getId());
            add("passwordwlcniubi"+user.getPassword());
            add("realnamewlcniubi"+user.getRealname());
            add("universitywlcniubi"+user.getUniversity());
            add("departmentwlcniubi"+user.getDepartment());
            add("mailwlcniubi"+user.getMail());
        }};
        ArrayList<String> user_info = new ArrayList<>();
        String user_info_path = projectPath + "/file_data/user/" + user.getId() + "/information";

//        修改数据库
        updateUserInformation(changeField_Data);
//        修改用户文件
        user_info = readUserInfor(user_info_path);
        user.setPassword(user.getPassword().equals("null")?user_info.get(1):user.getPassword());
        user.setRealname(user.getRealname().equals("null")?user_info.get(2):user.getRealname());
        user.setUniversity(user.getUniversity().equals("null")?user_info.get(3):user.getUniversity());
        user.setDepartment(user.getDepartment().equals("null")?user_info.get(4):user.getDepartment());
        user.setMail(user.getMail().equals("null")?user_info.get(5):user.getMail());
        saveUserInfor(user,user_info_path);
    }

    /**
     * 计算搜索结果并存储到磁盘，并返回需要显示内容
     * @param user_cookie_value
     * @param projectPath
     * @param base
     * @param keyword
     * @return
     * @throws IOException
     */
    public static String setSearchResult(String user_cookie_value,String projectPath,String base,String keyword) throws IOException{
        String user_file_Path = projectPath+"/file_data/user/"+user_cookie_value.split("wlcniubi")[0]+"/";

        ArrayList<ArrayList<String>> search_result = QmDao.searchQM_data_by_keyword(base,keyword);


        UserDao.saveUserSearchResult(search_result,user_file_Path+"searchResult");

        String last_result = "";
        if (search_result.size()>0){
            ArrayList<String> process_result = new ArrayList<>();
            //查找内容显示
            for (ArrayList<String> search_result_row : search_result){

                if(search_result_row.get(7).equals("QM_CalculationObject_SolventSolute")) {
                    String[] show_content = {search_result_row.get(0), search_result_row.get(1), search_result_row.get(2), search_result_row.get(26), search_result_row.get(7).split("_")[2]};
                    process_result.add(StringUtils.join(show_content,"lxyniubi"));
                }
                else {
                    String[] show_content = {search_result_row.get(0), search_result_row.get(1), search_result_row.get(2), "null", search_result_row.get(7).split("_")[2]};
                    process_result.add(StringUtils.join(show_content,"lxyniubi"));
                }
            }
            last_result = StringUtils.join(process_result.toArray(),"wlcniubi");
        }
        return last_result;
    }

    /**
     * 获取选择后的搜索结果
     * @param user_cookie_value
     * @param projectPath
     * @param select_data_id
     * @return
     * @throws IOException
     */
    public static String getSearchResult(String user_cookie_value,String projectPath,String select_data_id) throws IOException{

        String user_file_Path = projectPath+"/file_data/user/"+user_cookie_value.split("wlcniubi")[0]+"/";
        ArrayList<ArrayList<String>> search_result = UserDao.getUserSearchResult(user_file_Path+"searchResult");
        ArrayList<ArrayList<String>> select_result = new ArrayList<>();

        for (ArrayList<String> result : search_result){
            if (select_data_id.contains(result.get(0))){
                select_result.add(result);
            }
        }
        ArrayList<String> select_result_str = new ArrayList<>();
        for (ArrayList<String> select_result_row : select_result){
            select_result_str.add(StringUtils.join(select_result_row.toArray(),"lxyniubi"));
        }
        return StringUtils.join(select_result_str.toArray(),"wlcniubi");
    }


}
